﻿using System;

namespace DotNetStar.OpenSDK.QQ
{
    using System.Net.Http;
    using OAuth;
    using Newtonsoft.Json;

    /// <summary>
    /// 使用 QQ互联 获取令牌凭据。
    /// </summary>
    /// <seealso cref="AccessTokenApiRequest{QQOAuthApiResponse}" />
    /// <seealso cref="OAuth.AccessTokenApiRequest{TResponse}" />
    public class QQAccessTokenApiRequest : AccessTokenApiRequest<QQOAuthApiResponse>
    {
        /// <summary>
        /// 初始化 <see cref="QQAccessTokenApiRequest"/> 类的新实例。
        /// </summary>
        /// <param name="config">OAuth2.0 认证的配置。</param>
        /// <param name="code">授权码。需要先使用 <see cref="QQAuthorizeCodeApiRequest" /> 模块申请获得。</param>
        public QQAccessTokenApiRequest(OAuthConfig config, string code)
            : base("https://graph.qq.com/oauth2.0/token", config, code)
        {
        }

        /// <summary>
        /// 获取授权类型。
        /// </summary>
        public string Grant_Type => "authorization_code";
        /// <summary>
        /// 获取客户端 Id。
        /// </summary>
        public string Client_Id => base.Config.ClientId;

        /// <summary>
        /// 获取客户端应用分配的密钥。
        /// </summary>
        public string Client_Secret => base.Config.ClientKey;

        /// <summary>
        /// 获取配置的回调url。
        /// </summary>
        public string Redirect_uri => base.Config.RedirectUri;


        /// <summary>
        /// 处理自定义请求结果的回调。
        /// </summary>
        /// <param name="httpResponse">Http 请求响应的 <see cref="T:System.Net.Http.HttpResponseMessage" /> 实例。</param>
        /// <returns>
        /// 自定义的处理结果。
        /// </returns>
        public override QQOAuthApiResponse ResponseHandler(HttpResponseMessage httpResponse)
        {
            var responseString = httpResponse.GetContentAsString();

            try
            {
                var keyValue = new KeyValueCollection(responseString);

                return JsonConvert.DeserializeObject<QQOAuthApiResponse>(keyValue.ToJson());
            }
            catch (Exception)
            {
                responseString = responseString.Replace("callback(", string.Empty).TrimEnd();
                responseString = responseString.TrimEnd(';');
                responseString = responseString.TrimEnd(')');
                return JsonConvert.DeserializeObject<QQOAuthApiResponse>(responseString);
            }

        }
    }
}
